<template>
  <view class="tab-wrap">
    <scroll-view scroll-x class="scroll-container" :scroll-left="scrollLeft" scroll-with-animation>
      <view v-for="(item,index) of tabList" :key="index"  :data-index="index" @click="initScroll" :id="`i-${index}`"  class="item" :class="{active: currentIndex === index}">{{item}}</view>
    </scroll-view>
  </view>
</template>
<script>
export default {
  name: 'tab',
  props: {
    currentIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      tabList: ['语文','数学', '英语','物理', '化学', '生物', '政治', '历史', '地理', '体育' ,'美术', '信息技术'],
      scrollLeft: 0,
      prevScrollLeft: 0
    }
  },
  watch:{
    currentIndex: {
      handler: function(index) {
        let left
        const _this = this
        const query = uni.createSelectorQuery().in(this).selectAll('.item');
        query.fields({
          size: true,
          rect: true,
        }, res => {
          left = Math.round(res[index].left)
        }).exec();
        const parent = uni.createSelectorQuery().in(this).select('.scroll-container')
        parent.fields({
          size: true,
          scrollOffset: true
        }, res => {
          left += Math.round(res.scrollLeft)
          _this.selectnode(index, left)
        }).exec();
      }
    }
  },
  methods: {
    initScroll(e) {
      const left = e.currentTarget.offsetLeft
      const idx = e.currentTarget.dataset.index
      this.selectnode(idx, left)
    },
    selectnode(idx, left) {
      const query = uni.createSelectorQuery().in(this).selectAll('.item');
      query.fields({
        size: true,
        scrollOffset: true
      }, res => {
        this.swiper(res[idx].width, left, idx)
      }).exec();
    },
    // 计算滚动距离
    swiper(width, left, idx) {
    // 获取屏幕宽度
      const pageX = uni.getSystemInfoSync().windowWidth
      const scrollLeft = left - pageX / 2 + width / 2
      this. scrollLeft = scrollLeft
      this.$emit('update:currentIndex', idx)
  },
  }
}
</script>
<style lang="scss" scoped>
.tab-wrap{
  width: 100%;
  background-color: #fff;
  padding-top: 90upx;
  box-sizing: border-box;
  white-space: nowrap;
  .scroll-container{
    box-shadow:2upx 9upx 36upx 4upx rgba(0, 0, 0, 0.13);
    .item {
      display: inline-block;
      margin-right: 30upx;
      padding: 0 20upx;
      font-size: 30upx;
      color: #999;
      line-height: 90upx;
      &:active{
        background-color: #f5f5f5;
      }
    }
    .active{
      color: #0D84D5;
    }
  }
}
</style>
